import {routerRedux} from 'dva/router';
import {AccountLogin, fakeMobileLogin} from '../services/api';

export default {
    namespace: 'login',

    state: {
        status: undefined,
        access_token: sessionStorage.getItem('access_token'),
        role:'order_admin'
    },

    effects: {
        * accountSubmit({payload}, {call, put}) {
            yield put({
                type: 'changeSubmitting',
                payload: true,
            });
            const response = yield call(AccountLogin, payload);
            console.log(response)
            yield put({
                type: 'changeLoginStatus',
                payload: response,
            });
            yield put({
                type: 'changeSubmitting',
                payload: false,
            });
        },
        * mobileSubmit(_, {call, put}) {
            yield put({
                type: 'changeSubmitting',
                payload: true,
            });
            const response = yield call(fakeMobileLogin);
            yield put({
                type: 'changeLoginStatus',
                payload: response,
            });
            yield put({
                type: 'changeSubmitting',
                payload: false,
            });
        },
        * logout(_, {put}) {
            sessionStorage.removeItem("access_token")
            yield put({
                type: 'changeLoginStatus',
                payload: {
                    access_token: null,
                },
            });
            yield put(routerRedux.push('/login'));
        },
    },

    reducers: {
        changeLoginStatus(state, {payload}) {
            return {
                ...state,
                status: payload.status,
                type: payload.type,
                access_token: payload.data ? payload.data.access_token : null,
            };
        },
        changeSubmitting(state, {payload}) {
            return {
                ...state,
                submitting: payload,
            };
        },
    },
};
